/**
 * Created by Administrator on 2017/7/20.
 */
(function() {
    "use strict";
    var app = angular.module("angularApp");
    app.controller('instanceCtrl', function ($scope,$rootScope, $http,$uibModal,$stateParams,fac, $q) {
        var sceneId = $stateParams.id
        console.log(sceneId);



        $scope.search = {sceneId:sceneId};
        $scope.pageModel = {};
        console.log($stateParams.id);
     /*   function getParam(url,name) {
            return url.match(new RegExp('[?#&]?' + name + '=([^?#&]+)', 'i')) ? RegExp.$1 : '';
        }*/

        $scope.find = function(pageNo){
            $.extend($scope.search,{currentPage:pageNo||$scope.pageModel.currentPage||1,pageSize:$scope.pageModel.pageSize||200});
            $scope.search.pageIndex = $scope.search.currentPage-1;
            fac.getPageResult("../instance/list",$scope.search,function(data){
                $scope.pageModel = data;
            });
        };
        $scope.find(1);

        $scope.$on("refreshStyleType",function(){
            $scope.find(1);
        })
      /*  $scope.addXml = function () {
            fac.upload({ url: "/style/uploadXml", accept: "text/xml, application/xml",params:{'sceneId':sceneId} }, function (resp) {
                if (resp.code == 0 ) {
                    $rootScope.elementEnum.forEach(function(n){delete n.pageModel});
                    msg("导入成功！")
                } else {
                    alert(resp.msg);
                }
            })
        }*/
        $scope.listStyles = function(TextSymbolizer){
            return  $scope.curInstance.elementList.find(function(n){return n.id == 'text' })
                .styles.filter(function(m){return m.data.find(function(l){ return l.texttype == TextSymbolizer})})
        }
        $scope.setCurTextStyle = function(item,textName){
            if($scope.curTextStyle && $scope.curTextStyle.ruleId == item.id){
                delete $scope.curTextStyle.ruleId;
                return;
            }
            var textStyleList = $scope.curInstance.elementList.find(function(n){return n.id == 'text'}).styles;
            $scope.curTextStyle =  textStyleList.find(function(n){return n.id == textName});
            $scope.curTextStyle.ruleId = item.id;
        }


        $scope.listDicts = function(element){
            return $scope.curInstance.dictTypeList.find(function(n){return n.id == element}).data;
        }


        //添加与保存instance
        $scope.showEditModal = function(item,copy){
            var tt = angular.extend({},item);
            if(copy){
               delete tt.id;
            }
            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/instance.modal.html',
                controller: 'instanceModalCtrl'
                ,resolve: {item: tt}
            });
            modal.result.then(function () {
                $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };


        $scope.addDict = function(type){
            type.data = type.data||[];
            var item = {edit:true,copy:{instanceId:$scope.curInstance.id,element:type.id}};
            type.data.push(item);
        };
        $scope.editDict = function(item){
            item.copy = angular.extend({},item);
            item.edit = true;
        };
        $scope.cancelDict = function(type,item){
            if(!item.id){
                type.data.splice(type.data.indexOf(item), 1)
            }else{
                delete item.copy;
                item.edit = false;
            }
        };

        $scope.saveDict = function (form,item,url) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            $http.post(url, item.copy).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $.extend(item,resp.data);
                    item.edit = false;
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
        $scope.delDict = function (type,item,table) {
            confirm("确认删除该样式函数吗？",function(){
                $http.get("../dict/del", {params:{ids:item.id,table:table}}).success(function (resp, status, headers, config) {
                    if (resp.code === 0) {
                        type.data.splice(type.data.indexOf(item),1);
                        msg("删除成功!");
                    } else {
                        alert(resp.msg);
                    }
                })
            });
        }

        $scope.addRule = function(style){
            style.data = style.data||[];
            var item = {edit:true,copy:{instanceId:$scope.curInstance.id,styleTypeId:style.id}};
            style.data.push(item);
        };

        $scope.editRule = function(item){
            item.copy = angular.extend({},item);
            item.edit = true;
        };
        $scope.cancelRule = function(style,item){
            if(!item.id){
                style.data.splice(style.data.indexOf(item), 1)
            }else{
                delete item.copy;
                item.edit = false;
            }
        };

        $scope.saveRule = function (form,item,url) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            $http.post(url, item.copy).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $.extend(item,resp.data);
                    item.edit = false;
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
        $scope.delRule = function (style,item) {
            confirm("确认删除该样式规则吗？",function(){
                $http.get("../rule/del", {params:{ids:item.id,element:style.element}}).success(function (resp, status, headers, config) {
                    if (resp.code === 0) {
                        style.data.splice(style.data.indexOf(item),1);
                        msg("删除成功!");
                    } else {
                        alert(resp.msg);
                    }
                })
            });
        }
        $scope.combineRules = function (element,style) {
            var modal = $uibModal.open({
                animation: false,
                size:'lg',
                templateUrl: 'view/instance/ruleSplit.modal.html',
                controller: 'ruleSplitModalCtrl'
                ,resolve: {style: function(){return style},instanceId:function(){return $scope.curInstance.id}}
            });
            modal.result.then(function () {
                $scope.queryRule(element,style);
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        }
        $scope.queryRule = function(element,style){
            var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,element:element.id,styleTypeId:style.id}
            fac.getPageResult("../rule/list",search,function(resp){
                style.data = resp.data;
            });
        }

        /*$scope.splitRule = function (style,item) {
            confirm("确认删除该样式规则吗？",function(){
                $http.get("../rule/del", {params:{ids:item.id,element:style.element}}).success(function (resp, status, headers, config) {
                    if (resp.code === 0) {
                        style.data.splice(style.data.indexOf(item),1);
                        msg("删除成功!");
                    } else {
                        alert(resp.msg);
                    }
                })
            });
        }*/
       /* $scope.showColorModal = function(item,type){

            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/color.modal.html',
                controller: 'colorModalCtrl'
                ,resolve: {item: angular.extend({},item)}
            });
            modal.result.then(function (color) {
                if(item.id){
                    angular.extend(item,color);
                }else{
                    type.data = type.data||[];
                    type.data.splice(0,0,color);
                }
               // $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.showFontModal = function(item,type){
            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/font.modal.html',
                controller: 'fontModalCtrl'
                ,resolve: {item: angular.extend({},item)}
            });
            modal.result.then(function (font) {
                if(item.id){
                    angular.extend(item,font);
                }else{
                    type.data = type.data||[];
                    type.data.splice(0,0,font);
                }
                // $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.showDashLineModal = function(item,type){
            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/dashLine.modal.html',
                controller: 'dashLineModalCtrl'
                ,resolve: {item: angular.extend({},item)}
            });
            modal.result.then(function (dashLine) {
                if(item.id){
                    angular.extend(item,dashLine);
                }else{
                    type.data = type.data||[];
                    type.data.splice(0,0,dashLine);
                }
                // $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };
*/
       function findRules(e){
           if(!e.promiss){
               var deferred = $q.defer();
               getRequiredPromises(e).then(function(){
                   $http.get("../styleType/listByElement?element="+e.id).success(function(resp){
                       if(resp.code == 0){
                           e.styles = resp.data;
                           var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,element:e.id}
                           fac.getPageResult("../rule/list",search,function(resp){
                               e.styles.forEach(function(style){
                                   style.data = resp.data.filter(function(n){return n.styleTypeId == style.id })
                               })
                               deferred.resolve();
                           });
                       }
                   })
               })
               e.promiss = deferred.promise;
           }
           return e.promiss;
       }


       function findDicts(e){
           if(!e.promiss){
               var deferred = $q.defer();
               var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,dictType:e.id}
               fac.getPageResult("../dict/list",search,function(resp){
                   e.data = resp.data;
                   deferred.resolve(resp.data);
               });
               e.promiss = deferred.promise;
           }
           /*if(!e.data){

           }*/
           return e.promiss;
       }

        $scope.findRules = function(e){
            findRules(e);
        };

        $scope.findDicts = function(e){
            findDicts(e);
        };



        //获取样式依赖的样式 （点，线，箭头 依赖 文本样式，文本样式依赖颜色和字体）
        function getRequiredStylePromise(instance,ele){
            var listPromises = [];
            if(['point','line','arrow'].indexOf(ele.id)>-1){
                listPromises.push(findRules(getElement(instance,'text')));
            }
            return listPromises;
        }

        function getElement(instance,eleId){
            return instance.elementList.find(function(n){return n.id == eleId})
        }

        function getDictType(instance,dictId){
            return instance.dictTypeList.find(function(n){return n.id == dictId})
        }

        //获取样式依赖的函数
        function getRequiredDictPromise(instance,ele){
            var listPromises = [];
            switch (ele.id){
                case "text":
                    listPromises.push(findDicts(getDictType(instance,"font")));
                    listPromises.push(findDicts(getDictType(instance,"text")));
                    break;
                case "line":
                    listPromises.push(findDicts(getDictType(instance,"line")));
                    listPromises.push(findDicts(getDictType(instance,"text")));
                    listPromises.push(findDicts(getDictType(instance,"dashLine")));
                    break;
                case "polygon":
                    listPromises.push(findDicts(getDictType(instance,"polygon")));
                    break;
                case "building":
                    listPromises.push(findDicts(getDictType(instance,"building")));
                    break;
                case "arrow":
                    listPromises.push(findDicts(getDictType(instance,"arrow")));
                    break;
            }
            return listPromises;
        }

        function getRequiredPromises(ele){
            var listPromises = [];
            listPromises.push.apply(listPromises,getRequiredStylePromise($scope.curInstance,ele));
            listPromises.push.apply(listPromises,getRequiredDictPromise($scope.curInstance,ele));
            return $q.all(listPromises);
        }





        $scope.showDetail = function(item){
            $scope.curInstance = item;
            if(!item.elementList){
                item.elementList = $.extend(true,[],$rootScope.elementList);
                item.dictTypeList = $.extend(true,[],$rootScope.dictTypeList);
            }
            $scope.search.showOn = true;
        };
        //删除
        $scope.del = function(item){
            confirm("确认删除该样式吗？",function(){
                $http.get("../instance/del?ids="+item.id).success(function(resp){
                    if(resp.code === 0){
                        $scope.find();
                    }else{
                        alert(resp.msg);
                    }
                })
            });
        }


    });



    app.controller('instanceModalCtrl', function($scope,$http,$uibModalInstance,fac,item) {
        $scope.item = item;

        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            var url = item.id?"/instance/update":"/instance/copy";
            var message = item.id?"保存成功!":"复制成功！";
            $http.post(url, item).success(function (data, status, headers, config) {
                if (data.code === 0) {
                    $uibModalInstance.close();
                    msg(message);
                } else {
                    alert(data.msg);
                }
            })
        }
    });

    app.controller('ruleSplitModalCtrl', function($scope,$http,$uibModalInstance,fac,style,instanceId) {

        $scope.style = style;
        style.data.sort(function(a,b){return a.scale.split(",")[0]-b.scale.split(",")[0]});
        //{no:1,can:true},{no:2,can:true},{no:3,can:true},{no:4,can:true},{no:5,can:true},{no:6,can:true},{no:7,can:true},{no:8,can:true}
        $scope.scissors = []
        for(var i =0;i<style.data.length;i++){
            var nums = style.data[i].scale.split(",");
            var from = parseInt(nums[0]);
            var to = parseInt(nums[1]);
            while(from < to){
                if(from >0 ){
                    $scope.scissors.push({ruleId:style.data[i].id,no:from,can:true})
                }
                from ++;
            }
            var scissor = {ruleId:style.data[i].id,no:to,cut:true};
            if(i==style.data.length-1){
                scissor.cut = false;
            }else if( fac.compare(style.data[i],style.data[i+1])){
                scissor.can = true;
            }else{
                scissor.can = false;
            }
            $scope.scissors.push(scissor)
        }
        $scope.scales = style.data.map(function(n){return {ruleId:n.id,from:n.scale.split(",")[0],to:n.scale.split(",")[1]}});

        $scope.caluCut = function(scissor){
            scissor.cut=!scissor.cut;
            getRet();
        }
        function getRet () {
            $scope.scales = [];
            var cuts = $scope.scissors.filter(function(n){return n.cut});
            var from = 0;
            cuts.forEach(function(n){
                $scope.scales.push({from:from,to:n.no,ruleId:n.ruleId});
                from = n.no+1;
            })
            var lastScissor = $scope.scissors[$scope.scissors.length-1];
            $scope.scales.push({from:from,to:lastScissor.no,ruleId:lastScissor.ruleId});
        }

        $scope.save = function () {
            var combineBean = {instanceId:instanceId,element:style.element,styleTypeId:style.id,rules:$scope.scales}
            $http.post("../rule/combine", combineBean).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close();
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

  /*  app.controller('colorModalCtrl', function($scope,$http,$uibModalInstance,fac,item) {
        $scope.item = item;
        $scope.$on('colorPicked', function(event, color) {
            item.color = color;
        });
        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            $http.post("../dict/saveColor", item).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close(resp.data);
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

    app.controller('fontModalCtrl', function($scope,$http,$uibModalInstance,item) {
        $scope.item = item;
        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            $http.post("../dict/saveFont", item).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close(resp.data);
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

    app.controller('dashLineModalCtrl', function($scope,$http,$uibModalInstance,item) {
        $scope.item = item;
        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            $http.post("../dict/saveDashLine", item).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close(resp.data);
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });*/




})();